﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
using Domain;
using Domain.Entity;
using EmailMarketingDao;

namespace EmailMarketingDomain
{
    /// <summary>
    /// 本地发信邮局
    /// </summary>
    public class NativePostOffice
    {
        public static int AllFinishedTaskCount { get; set; }//累计已完成任务数
        public static int ALLSuccessFinishedTaskCount { get; set; }//累计已成功完成任务数
        public static Letter LetterTemplate { get; set; }//信件模板
        public static int MaxLetterPoolCount { get; set; }//最大发信队列大小
        public static bool EnableActivitiesUserEmail { get; set; }//启用活跃用户发送
        private static Queue<Letter> _letters = new Queue<Letter>();//待发信队列
        private bool _isWork = false;
        public static string StopWorkReason { get; set; }
        public static int WorkSpeed { get; set; }
        public static DateTime StarTime { get; set; }
        public static DateTime EndTime { get; set; }
        private static NativePostOffice _nativePostOffice;
        private static readonly object _syncBoot = new object();
        private NativePostOffice()
        {

        }
        public static NativePostOffice GetInstance()
        {
            if (_nativePostOffice == null)
            {
                lock (_syncBoot)
                {
                    if (_nativePostOffice == null)
                    {
                        _nativePostOffice = new NativePostOffice();
                    }
                }
            }
            return _nativePostOffice;
        }
        /// <summary>
        /// 邮局是否在工作
        /// </summary>
        public bool IsWorking { get { return _isWork; } }
        /// <summary>
        ///  开始工作
        /// </summary>
        public void StartToWork()
        {
            _isWork = true;
            StarTime = DateTime.Now;
            DoWork();
        }
        /// <summary>
        /// 停止工作
        /// </summary>
        public void StopToWork(string reason = "")
        {
            _isWork = false;
            EndTime = DateTime.Now;
            StopWorkReason = reason;
        }
        /// <summary>
        /// 邮局工作
        /// </summary>
        private void DoWork()
        {
            while (_isWork)
            {
                try
                {
                    if (LetterTemplate == null)
                    {
                        StopToWork("信件模板标题或内容为空");
                        return;
                    }
                    Thread.Sleep(WorkSpeed);//工作速度
                    //队列还有信件，则休息1秒
                    if (_letters.Count > 0)
                    {
                        Thread.Sleep(1000);
                        continue;
                    }
                    string[] emails = new string[] { }; ;
                    if (EnableActivitiesUserEmail)
                        emails = QQEmailDao.GetUnSendAndActivitiesUserEmailAddress(MaxLetterPoolCount);
                    else
                        emails = QQEmailDao.GetUnSendEmailAddress(MaxLetterPoolCount);
                    foreach (var email in emails)
                    {
                        Letter letter = new Letter()
                        {
                            ToSendAddress = email,
                            Content = LetterTemplate.Content + "(" + DateTime.Now + ")",
                            Title = LetterTemplate.Title + "(" + DateTime.Now + ")",
                        };
                        _letters.Enqueue(letter);
                        QQEmailDao.UpdateqqEmailHasSend(email, true);
                    }

                }
                catch (Exception ex)
                {
                    CustomsLog.WriteExceptionErrorLog("本地邮局工作出错", ex);
                }
            }
        }
        /// <summary>
        /// 从队列中取出一个信件
        /// </summary>
        /// <returns></returns>
        public static Letter GetLetter()
        {
            Letter letter = null;
            if (_letters.Count != 0)
            {
                try
                {
                    letter = _letters.Dequeue();
                }
                catch (Exception)
                {

                }
            }

            return letter;
        }
        /// <summary>
        /// 将发送地址加入队列
        /// </summary>
        /// <param name="letter"></param>
        public static void AddLetter(Letter letter)
        {
            if (letter == null) return;
            _letters.Enqueue(letter);
        }
        /// <summary>
        /// 获取队列的长度
        /// </summary>
        /// <returns></returns>
        public static int GetLetterQueueLength()
        {
            return _letters.Count;
        }
    }
}
